package com.yellowpage.nsp.action;

import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;

import com.yellowpage.nsp.data.NspLogger;
import com.yellowpage.nsp.service.NspLoggerService;
import com.yellowpage.white.common.Configuration;
import com.yellowpage.white.struts.BaseAction;

public class NspLoggerCountJFreeChartAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	

    public String RESULT_QUERY = "query";
    public String RESULT_ADD = "add";
	public String RESULT_EDIT = "edit";
	public String RESULT_NSPCOUNT = "nsp_count";
	public String RESULT_NSPCOUNT_INFO = "nsp_count_info";
	
	
	private Configuration configuration;
	
	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}
	
	private List<NspLogger> nspLoggerList = new ArrayList<NspLogger>();
	private List<Map> resultList = new ArrayList<Map>();
	
	private NspLogger nspLogger;
	private NspLoggerService nspLoggerService;
	
	private String selectedId;	
	private String[] selectedIds;	
	private String message;
	
	private String JFreeChartshow;
	
	private String query_requestType_seach;
	private String query_requestTime;
	private String query_requestTime_end;

	private Map requestTypeMap = new HashMap();
	
	public void prepare() {
		super.prepare();
		requestTypeMap=nspLoggerService.getrequestTypeMap();
		if (this.selectedId != null && !this.selectedId.equals("")) {
			this.nspLogger = nspLoggerService.getNspLogger(Long.parseLong(selectedId));
		}
	}
	
	//日志数据统计
	public String countNspLoggerJFreeChart() {
		return RESULT_NSPCOUNT;
	}
	  
	public String countNspLoggerJFreeChartQuery() throws ServletException {
		
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
		if(query_requestTime == null){
			query_requestTime = sFormat.format(new Date());
		}
		if(query_requestTime_end == null){
			query_requestTime_end = sFormat.format(new Date());
		}
		
		Map queryMap = new HashMap();	
		queryMap.put("requestTime", query_requestTime);
		queryMap.put("requestTimeEnd", query_requestTime_end);
		queryMap.put("requestType", query_requestType_seach);
		    	
		
		if(!query_requestType_seach.isEmpty()){
			resultList = nspLoggerService.getseachInfo(queryMap);
			System.out.print(resultList);
		}
		
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
	    
	    
	    for (Map map : resultList) {
	    	dataset.addValue((Number) map.get("ALLSUM"),"'"+map.get("REQUEST_TYPE")+"'", "'"+map.get("DATETIME")+" "+map.get("TIME")+"'");  
			
	    }
	    
	    HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType( "text/html;charset=GBK "); 
		String path = request.getSession().getServletContext().getRealPath("/nspjfreechart");		
		FileOutputStream fos=null;	      
		 File file = new File(path);  
		        if(!file.exists()){  
		        	file.setExecutable(true); 
		        	file.setReadable(true);
		        	file.setWritable(true);
		            file.mkdir();  
		        }  

	      //折线图
	     JFreeChart chart = ChartFactory.createLineChart(  
	           "日志数据统计图表",           // 标题  
	           "时间",                      // 横坐标  
	           "数据总数",                     // 纵坐标  
	           dataset,                    // 数据  
	           PlotOrientation.VERTICAL,   // 竖直图表  
	           true,                       // 是否显示legend  
	           false,                      // 是否显示tooltip  
	           false                       // 是否使用url链接  
	       );  
	     
	     
	   
	        CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
	        //背景
	        categoryplot.setBackgroundPaint(Color.white);
	        //网格
	        categoryplot.setDomainGridlinesVisible(true);  
	      //设置背景网格线颜色
	        categoryplot.setDomainGridlinePaint(Color.BLACK); 
	        
	        categoryplot.setRangeGridlinePaint(Color.GRAY);
	      //没有数据说明
	        categoryplot.setNoDataMessage("没有数据");
	      
			  
			 //标题
			TextTitle textTitle = chart.getTitle();
			textTitle.setFont(new Font("黑体", Font.PLAIN, 20));     
			//横轴
			CategoryAxis domainAxis = categoryplot.getDomainAxis(); 
			domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); 
			domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));  
			domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 22));  
			//纵轴
			NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
			numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));  
			numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 22));  
			
			chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));
			//折线
			 LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();
			 lineandshaperenderer.setSeriesPaint(0, Color.black);   
			 //数据点
			 lineandshaperenderer.setBaseShapesVisible(true); 
				// 显示折点数据
			 lineandshaperenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		     lineandshaperenderer.setBaseItemLabelsVisible(true);
		     
		     
			    SimpleDateFormat formatter = new SimpleDateFormat("ss");
			    Date currentTime = new Date();
			    String dateString = formatter.format(currentTime);
	      try {  
	          fos = new FileOutputStream(path  + "/nspcountjfreechart"+dateString+".png");
	          ChartUtilities.writeChartAsPNG(fos, chart, 1000, 550);  	
		      
	      } catch (FileNotFoundException e) {  
	       e.printStackTrace();  
	      } catch (IOException e) {  
	       e.printStackTrace();  
	      } finally {  
	          try {  
	           if(fos != null){  
	            fos.close();  
	            
	           }  
	       } catch (IOException e) {  
	        e.printStackTrace();  
	       }  
	      }  
	     
	  	String path2 = request.getContextPath();
	      JFreeChartshow=path2+"/nspjfreechart/nspcountjfreechart"+dateString+".png";

		return RESULT_NSPCOUNT;
	}
	
	/**
	 * getters and setters
	 * 
	 * @return
	 */
	 public void setNspLogger(NspLogger nspLogger) {
		this.nspLogger = nspLogger;
	}
	
	public NspLogger getNspLogger() {
		return nspLogger;
	}
	 
	 
	 public void setNspLoggerService(NspLoggerService nspLoggerService) {
		this.nspLoggerService = nspLoggerService;
	}
	
	public List<NspLogger> getNspLoggerList() {
		return nspLoggerList;
	}
	
	public void setNspLoggerList(List<NspLogger> nspLoggerList) {
		this.nspLoggerList = nspLoggerList;
	}
	
	public String getSelectedId() {
		return selectedId;
	}
	
	public void setSelectedId(String selectedId) {
		this.selectedId = selectedId;
	}
	
	public String[] getSelectedIds() {
		return selectedIds;
	}
	
	public void setSelectedIds(String[] selectedIds) {
		this.selectedIds = selectedIds;
	}
	
	public String getMessage() {
		return message;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}
	
	public List<Map> getResultList() {
		return resultList;
	}
	
	public void setResultList(List<Map> resultList) {
		this.resultList = resultList;
	}
	
	public String getQuery_requestTime() {
	    return this.query_requestTime;
	}
	
	public void setQuery_requestTime(String requestTime){
	    this.query_requestTime = requestTime;
	}      
	
	
	public String getQuery_requestType_seach() {
		return query_requestType_seach;
	}

	public void setQuery_requestType_seach(String query_requestType_seach) {
		this.query_requestType_seach = query_requestType_seach;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public NspLoggerService getNspLoggerService() {
		return nspLoggerService;
	}

	public Map getRequestTypeMap() {
		return requestTypeMap;
	}
	public void setRequestTypeMap(Map requestTypeMap) {
		this.requestTypeMap = requestTypeMap;
	}
	
	public String getQuery_requestTime_end() {
		return query_requestTime_end;
	}
	
	public void setQuery_requestTime_end(String query_requestTime_end) {
		this.query_requestTime_end = query_requestTime_end;
	}

	public String getJFreeChartshow() {
		return JFreeChartshow;
	}

	public void setJFreeChartshow(String jFreeChartshow) {
		JFreeChartshow = jFreeChartshow;
	}
	
}
